'''
Created on 2012-10-26

@author: DANG Zhengfa
'''
# -*- coding: utf-8 -*-
# import logging
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import blobstore
import utilities
import urllib
import logging
import random


class BaseModel(db.Model):
    key_template = ""

    @property
    def str_key(self):
        return str(self.key())

    @property
    def id(self):
        return self.key().id()

    @property
    def keyname(self):
        return self.key().name()


class Setting(db.Model):
    host = db.StringProperty(default="skyalbum.zfdang.com")
    headline = db.StringProperty(default="Photo in Timeline")
    text = db.StringProperty(default="Description of this album")
    start_date = db.StringProperty(default="2012-09-18")


class DBPhoto(BaseModel):
    headline = db.StringProperty(default="")
    text = db.StringProperty(default="")
    start_date = db.StringProperty(default="")
    end_date = db.StringProperty(default="")

    photo_name = db.StringProperty(required=True, default="")
    public = db.BooleanProperty(default=False)
    mime = db.StringProperty()
    size = db.IntegerProperty()
    width = db.IntegerProperty(default=0)
    height = db.IntegerProperty(default=0)
    createdate = db.DateTimeProperty(auto_now_add=True)
    description = db.StringProperty(multiline=True, default="")
    blob_key = db.StringProperty()
    thumb_blob_key = db.StringProperty()

    @property
    def is_public(self):
        return self.public

    def remove(self):
        blobstore.delete(self.blob_key)
        blobstore.delete(self.thumb_blob_key)
        self.delete()

    # make sure it's consistent with routes in main.py
    def gen_url(self, prefix="/photo"):
        return "%s/%s" % (prefix, urllib.quote(self.photo_name.encode("UTF-8")))

    def gen_html_url(self, prefix="/html"):
        return "%s/%s" % (prefix, urllib.quote(self.photo_name.encode("UTF-8")))

    def gen_thumb_url(self, prefix="/photo/thumb"):
        return "%s/%s" % (prefix, urllib.quote(self.photo_name.encode("UTF-8")))

    @classmethod
    def create(cls, file_name, binary):
        oimg = images.Image(image_data=binary)  # for output_encoding
        # browser does not support orentation in exif, so use this 360 degrees rotrate to remove orientation
        nbinary = images.rotate(binary, 0, output_encoding=oimg.format, correct_orientation=images.CORRECT_ORIENTATION)
        del oimg
        img = images.Image(image_data=nbinary)
        thumb_binary = images.resize(nbinary, 640, 480, images.JPEG)

        # make sure filename is unique since we depends on this to get image_data
        results = cls.all().filter("photo_name =", file_name)
        if results.count() > 0:
            rands = random.randint(10000, 90000)
            logging.error("Filename %s duplicated, add random seed %d as prefix" % (file_name, rands))
            file_name = "%d_%s" % (rands, file_name)

        photo = cls(photo_name=file_name)
        photo.photo_name = file_name
        photo.size = len(nbinary)
        mime_type = utilities.get_img_type(nbinary)
        photo.mime = mime_type
        photo.width = img.width
        photo.height = img.height
        blob_key = utilities.create_blob_file(mime_type, nbinary, "%s" % (file_name))
        thumb_blob_key = utilities.create_blob_file(utilities.ImageMime.JPEG, thumb_binary, "thumb_%s" % (file_name))
        photo.blob_key = str(blob_key)
        photo.thumb_blob_key = str(thumb_blob_key)
        photo.save()
        return photo
